/*
 * Copyright 2024 ywcai
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

`include "defines.v"
`timescale 1ns/1ps

module regfile(
	input	wire				clk,
	input	wire				rst_n,

	input	wire				we_i,
	input	wire[`RegAddrBus]	waddr_i,
	input	wire[`RegDataBus]	wdata_i,
	input	wire				rs1_en_i,
	input	wire[`RegAddrBus]	rs1_addr_i,
	input	wire				rs2_en_i,
	input	wire[`RegAddrBus]	rs2_addr_i,

	output	reg[`RegDataBus]	rs1_data_o,
	output	reg[`RegDataBus]	rs2_data_o
	);

	reg[`RegDataBus] regs[0:`REG_NUM-1];
	integer loop;

	initial begin
		for (loop = 0; loop < `REG_NUM; loop = loop + 1) begin
			regs[loop] = `ZERO;
		end
	end

	always @(posedge clk) begin
		if (rst_n != `RESET_ENABLE) begin
			if ((we_i == `ENABLE) & (waddr_i != `REG_ZERO_ADDR)) begin
				regs[waddr_i] <= wdata_i;
			end
		end
	end

	always @(*) begin
		if (rst_n == `RESET_ENABLE | rs1_en_i == `DISABLE
            | rs1_addr_i == `REG_ZERO_ADDR) begin
			rs1_data_o = `ZERO;
		end else if (rs1_addr_i == waddr_i & we_i == `ENABLE) begin
			rs1_data_o = wdata_i;
		end else begin
			rs1_data_o = regs[rs1_addr_i];
		end
	end

	always @(*) begin
		if (rst_n == `RESET_ENABLE | rs2_en_i == `DISABLE
            | rs2_addr_i == `REG_ZERO_ADDR) begin
			rs2_data_o = `ZERO;
		end else if (rs2_addr_i == waddr_i & we_i == `ENABLE) begin
			rs2_data_o = wdata_i;
		end else begin
			rs2_data_o = regs[rs2_addr_i];
		end
	end

endmodule
